from flask import render_template, request, redirect, url_for, flash, abort
from flask_login import login_required, current_user
from app import app
from database import db
from utils import allowed_file
from models import Issue, Comment, Tag, Milestone, User, IssueHistory, File
import os
import uuid
from datetime import datetime
from views import main_bp

@main_bp.route('/')
@main_bp.route('/issues')
@login_required
def list_issues():
    # 获取过滤参数
    status = request.args.get('status', 'all')
    priority = request.args.get('priority', 'all')
    tag = request.args.get('tag', 'all')
    milestone = request.args.get('milestone', 'all')
    assignee = request.args.get('assignee', 'all')
    search = request.args.get('search', '')

    # 构建查询
    query = Issue.query

    # 应用过滤
    if status != 'all':
        query = query.filter_by(status=status)
    if priority != 'all':
        query = query.filter_by(priority=priority)
    if tag != 'all' and tag:
        query = query.join(Issue.tags).filter(Tag.name == tag)
    if milestone != 'all' and milestone:
        query = query.filter_by(milestone_id=milestone)
    if assignee != 'all' and assignee:
        query = query.filter_by(assignee_id=assignee)
    if search:
        query = query.filter(Issue.title.like(f'%{search}%') | Issue.description.like(f'%{search}%'))

    issues = query.order_by(Issue.updated_at.desc()).all()

    # 获取所有标签、里程碑和用户用于过滤
    all_tags = Tag.query.all()
    all_milestones = Milestone.query.all()
    all_users = User.query.all()

    return render_template('issues/list.html', issues=issues, all_tags=all_tags, 
                          all_milestones=all_milestones, all_users=all_users)

@main_bp.route('/issues/<int:issue_id>')
@login_required
def view_issue(issue_id):
    issue = Issue.query.get_or_404(issue_id)
    comments = Comment.query.filter_by(issue_id=issue_id).order_by(Comment.created_at).all()
    history = IssueHistory.query.filter_by(issue_id=issue_id).order_by(IssueHistory.changed_at.desc()).all()
    # 查询创建者信息
    creator = User.query.get(issue.created_by) if issue.created_by else None
    # 将User模型传递到模板中，以便在模板中查询用户信息
    return render_template('issues/view.html', issue=issue, comments=comments, history=history, creator=creator, User=User)

@main_bp.route('/issues/new', methods=['GET', 'POST'])
@login_required
def create_issue():
    if request.method == 'POST':
        title = request.form['title']
        description = request.form['description']
        priority = request.form['priority']
        tag_ids = request.form.getlist('tags')
        milestone_id = request.form['milestone']
        due_date = request.form['due_date']
        assignee_id = request.form['assignee']
        category = request.form['category']
        visibility = request.form['visibility']

        # 处理日期
        due_date_obj = datetime.strptime(due_date, '%Y-%m-%d') if due_date else None

        # 创建问题
        issue = Issue(
            title=title,
            description=description,
            priority=priority,
            due_date=due_date_obj,
            created_by=current_user.id,
            assignee_id=assignee_id if assignee_id else None,
            milestone_id=milestone_id if milestone_id else None,
            category=category,
            visibility=visibility
        )

        # 添加标签
        for tag_id in tag_ids:
            tag = Tag.query.get(tag_id)
            if tag:
                issue.tags.append(tag)

        db.session.add(issue)
        db.session.commit()

        # 处理上传的文件
        if 'files' in request.files:
            files = request.files.getlist('files')
            for file in files:
                if file and allowed_file(file.filename):
                    # 生成唯一文件名
                    filename = str(uuid.uuid4()) + '.' + file.filename.rsplit('.', 1)[1].lower()
                    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                    file.save(filepath)
                    
                    # 创建文件记录
                    file_obj = File(
                        filename=file.filename,
                        filepath=filename,
                        filetype=file.content_type,
                        filesize=os.path.getsize(filepath),
                        issue_id=issue.id,
                        uploaded_by=current_user.id
                    )
                    db.session.add(file_obj)
        
        db.session.commit()

        # 记录历史
        add_history(issue.id, 'create', None, 'Issue created', current_user.id)

        flash('Issue created successfully!', 'success')
        return redirect(url_for('main.view_issue', issue_id=issue.id))

    # 获取所有标签、里程碑和用户
    all_tags = Tag.query.all()
    all_milestones = Milestone.query.all()
    all_users = User.query.all()

    return render_template('issues/new.html', all_tags=all_tags, all_milestones=all_milestones, all_users=all_users)

@main_bp.route('/issues/<int:issue_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_issue(issue_id):
    issue = Issue.query.get_or_404(issue_id)

    # 检查权限 - 管理员可以编辑任何问题
    if not current_user.is_admin and current_user.id != issue.created_by and current_user.id != issue.assignee_id:
        abort(403)

    if request.method == 'POST':
        # 检查并记录更改
        if issue.title != request.form['title']:
            add_history(issue.id, 'title', issue.title, request.form['title'], current_user.id)
            issue.title = request.form['title']

        if issue.description != request.form['description']:
            add_history(issue.id, 'description', issue.description, request.form['description'], current_user.id)
            issue.description = request.form['description']

        if issue.status != request.form['status']:
            add_history(issue.id, 'status', issue.status, request.form['status'], current_user.id)
            issue.status = request.form['status']

        if issue.priority != request.form['priority']:
            add_history(issue.id, 'priority', issue.priority, request.form['priority'], current_user.id)
            issue.priority = request.form['priority']

        # 处理上传的文件
        if 'files' in request.files:
            files = request.files.getlist('files')
            for file in files:
                if file and allowed_file(file.filename):
                    # 生成唯一文件名
                    filename = str(uuid.uuid4()) + '.' + file.filename.rsplit('.', 1)[1].lower()
                    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                    file.save(filepath)
                    
                    # 创建文件记录
                    file_obj = File(
                        filename=file.filename,
                        filepath=filename,
                        filetype=file.content_type,
                        filesize=os.path.getsize(filepath),
                        issue_id=issue.id,
                        uploaded_by=current_user.id
                    )
                    db.session.add(file_obj)
        
        # 处理标签
        tag_ids = request.form.getlist('tags')
        old_tags = [str(tag.id) for tag in issue.tags]
        if set(old_tags) != set(tag_ids):
            issue.tags = []
            for tag_id in tag_ids:
                tag = Tag.query.get(tag_id)
                if tag:
                    issue.tags.append(tag)
            add_history(issue.id, 'tags', ', '.join(old_tags), ', '.join(tag_ids), current_user.id)

        # 处理里程碑
        milestone_id = request.form['milestone']
        if str(issue.milestone_id) != milestone_id:
            add_history(issue.id, 'milestone', issue.milestone_id, milestone_id, current_user.id)
            issue.milestone_id = milestone_id if milestone_id else None

        # 处理截止日期
        due_date = request.form['due_date']
        due_date_obj = datetime.strptime(due_date, '%Y-%m-%d') if due_date else None
        if issue.due_date != due_date_obj:
            old_due_date = issue.due_date.strftime('%Y-%m-%d') if issue.due_date else None
            new_due_date = due_date if due_date else None
            add_history(issue.id, 'due_date', old_due_date, new_due_date, current_user.id)
            issue.due_date = due_date_obj

        # 处理负责人
        assignee_id = request.form['assignee']
        if str(issue.assignee_id) != assignee_id:
            add_history(issue.id, 'assignee', issue.assignee_id, assignee_id, current_user.id)
            issue.assignee_id = assignee_id if assignee_id else None

        # 处理分类
        if issue.category != request.form['category']:
            add_history(issue.id, 'category', issue.category, request.form['category'], current_user.id)
            issue.category = request.form['category']

        # 处理可见性
        if issue.visibility != request.form['visibility']:
            add_history(issue.id, 'visibility', issue.visibility, request.form['visibility'], current_user.id)
            issue.visibility = request.form['visibility']

        issue.updated_at = datetime.utcnow()
        db.session.commit()

        flash('Issue updated successfully!', 'success')
        return redirect(url_for('main.view_issue', issue_id=issue.id))

    # 获取所有标签、里程碑和用户
    all_tags = Tag.query.all()
    all_milestones = Milestone.query.all()
    all_users = User.query.all()

    return render_template('issues/edit.html', issue=issue, all_tags=all_tags, 
                          all_milestones=all_milestones, all_users=all_users)

@main_bp.route('/issues/<int:issue_id>/comment', methods=['POST'])
@login_required
def add_comment(issue_id):
    issue = Issue.query.get_or_404(issue_id)
    content = request.form['content']

    comment = Comment(
        content=content,
        user_id=current_user.id,
        issue_id=issue_id
    )

    db.session.add(comment)
    db.session.commit()

    flash('Comment added successfully!', 'success')
    return redirect(url_for('main.view_issue', issue_id=issue_id))

@main_bp.route('/issues/<int:issue_id>/close', methods=['POST'])
@login_required
def close_issue(issue_id):
    issue = Issue.query.get_or_404(issue_id)

    # 检查权限 - 管理员可以关闭任何问题
    if not current_user.is_admin and current_user.id != issue.created_by and current_user.id != issue.assignee_id:
        abort(403)

    if issue.status != 'closed':
        add_history(issue.id, 'status', issue.status, 'closed', current_user.id)
        issue.status = 'closed'
        db.session.commit()
        flash('Issue closed successfully!', 'success')
    else:
        flash('Issue is already closed!', 'info')

    return redirect(url_for('main.view_issue', issue_id=issue_id))

# 辅助函数：添加历史记录
def add_history(issue_id, field_changed, old_value, new_value, user_id):
    history = IssueHistory(
        issue_id=issue_id,
        field_changed=field_changed,
        old_value=str(old_value),
        new_value=str(new_value),
        changed_by=user_id
    )
    db.session.add(history)
    db.session.commit()